package com.xiaoke.java1;

import java.lang.ref.SoftReference;

/**
 * @author yd
 * @version 1.0
 * @date 2022/3/10 20:35
 */
public class SoftReferenceTest {

    public static class User{
        public int id;
        public String name;

        public User(int id, String name) {
            this.id = id;
            this.name = name;
        }

        @Override
        public String toString() {
            return "User{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    '}';
        }
    }


    public static void main(String[] args) {

        //创建对象，建立软引用
        SoftReference<User> userSoftRef = new SoftReference<User>(new User(1, "xiaoke"));
        //从软引用中重新获得强引用对象
        System.out.println(userSoftRef.get());

        System.gc();
        System.out.println("After gc");

        //垃圾回收之后获得软引用的对象
        System.out.println(userSoftRef.get());//由于堆内存中空间足够，所以不会回收软引用的可达对象



        try {
            //让系统人为内存资源紧张
            byte[] b = new byte[1024 * 1024 * 7];
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //再次从软引用中获取数据
            System.out.println(userSoftRef.get());//在报oom回收之前,垃圾回收器会回收软引用的可达对象
        }


    }
}
